package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.record.DVALRecord;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计指定时间范围内的营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //存放begin到end的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //循环加入dateList代码
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();

        //将date转为LocaldateTime
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //将参数封装为map
            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            //计算营业额
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //封装返回结果
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();

    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getuserStatistics(LocalDate begin, LocalDate end) {
        //存放begin到end的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //循环加入dateList代码
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Long> totalList = new ArrayList<>();
        List<Long> newList = new ArrayList<>();
        //将date转为LocaldateTime
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //将参数封装为map
            Map totalMap = new HashMap<>();
            totalMap.put("end", endTime);

            Map newMap = new HashMap<>();
            newMap.put("begin", beginTime);
            newMap.put("end", endTime);

            //计算总用户量
            Long totalUser = userMapper.userByMap(totalMap);
            totalUser = totalMap == null ? 0L : totalUser;
            totalList.add(totalUser);

            //计算新用户总量
            Long newUser = userMapper.userByMap(newMap);
            newUser = newMap == null ? 0L : newUser;
            newList.add(newUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalList, ","))
                .newUserList(StringUtils.join(newList, ","))
                .build();
    }

    @Override
    public OrderReportVO getordersStatistics(LocalDate begin, LocalDate end) {
        //存放begin到end的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //循环加入dateList代码
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> sumList = new ArrayList<>();
        List<Integer> validList = new ArrayList<>();

        //将date转为LocaldateTime
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //将参数封装为map
            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);

            Integer sumOrders = orderMapper.orderByMap(map);

            map.put("status", Orders.COMPLETED);

            Integer validOrders = orderMapper.orderByMap(map);

            //计算订单相关数据
            sumOrders = sumOrders == null ? 0 : sumOrders;
            sumList.add(sumOrders);
            validOrders = validOrders == null ? 0 : validOrders;
            validList.add(validOrders);
        }
        Map map = new HashMap<>();
        Integer totalOrder = orderMapper.orderByMap(map);
        map.put("status", Orders.COMPLETED);
        Integer validOrder = orderMapper.orderByMap(map);

        validOrder = validOrder == null ? 0 : validOrder;
        totalOrder = totalOrder == null ? 0 : totalOrder;

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCompletionRate(validOrder == 0 ? 0.0 : validOrder / totalOrder)
                .orderCountList(StringUtils.join(sumList, ","))
                .totalOrderCount(totalOrder)
                .validOrderCount(validOrder)
                .validOrderCountList(StringUtils.join(validList, ","))
                .build();
    }

    /**
     * TOP10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10Statistics(LocalDate begin, LocalDate end) {
        List<GoodsSalesDTO> salesTop = orderMapper.getSalesTop(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        List<String> name = salesTop.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameRes = StringUtils.join(name, ",");

        List<Integer> nums = salesTop.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numRes = StringUtils.join(nums, ",");

        return SalesTop10ReportVO.builder()
                .nameList(nameRes)
                .numberList(numRes)
                .build();
    }

    /**
     * 导出Excel表格
     */
    @Override
    public void exportBussinessData(HttpServletResponse response) {
        //1.查询数据库,获取营业数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        //概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //2.通过POI将数据写入Excel表中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //创建Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //填充数据
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);

            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(data.getTurnover());
                row.getCell(3).setCellValue(data.getValidOrderCount());
                row.getCell(4).setCellValue(data.getOrderCompletionRate());
                row.getCell(5).setCellValue(data.getUnitPrice());
                row.getCell(6).setCellValue(data.getNewUsers());
            }


            //3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
